package sddz.foodmanage.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentTransaction;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.adapter.OrderAdapter;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.dialog.ImagePreviewDialog;
import sddz.foodmanage.fragment.CommoditylistFragment;
import sddz.foodmanage.model.CommodityBean;
import sddz.foodmanage.model.SelectOkBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.DoubleUtil;
import sddz.foodmanage.utils.GlobalParms;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;
import sddz.foodmanage.view.MyListView;

/**
 * @Date:2019/7/8
 * @Author:lbb
 */

public class SearchNewActivity extends BaseActivity implements OrderAdapter.ModifyCountInterface {


    @BindView(R.id.im_back)
    ImageView imBack;
    @BindView(R.id.home_sao_yi_sao)
    AutoLinearLayout homeSaoYiSao;
    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.ll_search)
    AutoLinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.lin_search)
    AutoLinearLayout linSearch;
    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.title_layout)
    AppBarLayout titleLayout;
    @BindView(R.id.tv_nodata)
    TextView tvNodata;
    @BindView(R.id.shangpinlist)
    MyListView shangpinlist;
    @BindView(R.id.news_trl)
    TwinklingRefreshLayout newsTrl;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.activity_search)
    AutoLinearLayout activitySearch;
    private OrderAdapter adapter = new OrderAdapter();
    private List<CommodityBean.DataBeanX.DataBean> list = new ArrayList<>();
    TextView weight;
    int number;
    ImageView jian;
    ImageView add;
    private int pages = 1;
    CommodityBean commoditybean;
    private List<CommodityBean.DataBeanX.DataBean> xuanzhonglist = new ArrayList<>();
    private String type;
    private ImagePreviewDialog previewDialog;
    private List<String> imageList = new ArrayList<>();
    private CommoditylistFragment listfragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        type = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(type) && type.equals("true")) {//推荐订单
            titleLayout.setVisibility(View.VISIBLE);
            linSearch.setVisibility(View.GONE);
            titleText.setText("推荐菜单");
            tvOk.setText("选好了");
            searchsp(pages);
        } else {// 搜索
            titleLayout.setVisibility(View.GONE);
            linSearch.setVisibility(View.VISIBLE);
            tvOk.setVisibility(View.VISIBLE);
            tvOk.setText("确定");
        }
        if (SpfUtils.getUserData(mActivity).getType() == 2) {//中队
            tvOk.setVisibility(View.VISIBLE);
        } else {//供应商,
            tvOk.setVisibility(View.GONE);
        }
    }

    private void initListener() {
        newsTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                pages = 1;
                searchsp(pages);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pages++;
                searchsp(pages);
            }
        });
        if (adapter != null) {
            adapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        }


    }

    private void initView() {
        imBack.setVisibility(View.VISIBLE);
        ProgressLayout progressLayout = new ProgressLayout(mActivity);
        progressLayout.setColorSchemeResources(R.color.colorPrimary);
        newsTrl.setHeaderView(progressLayout);
    }

    @OnClick({R.id.im_back, R.id.tv_search, R.id.tv_ok, R.id.title_navigation_icon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.im_back:
                finish();
                break;
            case R.id.tv_search:
                searchsp(pages);
                break;
            case R.id.tv_ok:// 确定按钮
                if (tvOk.getText().equals("确定")) {
                    getSelect();
                } else {
                    getSelect();
                }

                break;
            case R.id.title_navigation_icon:
                finish();
                break;
        }
    }

    //搜索商品
    private void searchsp(final int pages) {
        if (!TextUtils.isEmpty(type) && type.equals("false")) {
            if (TextUtils.isEmpty(editText.getText().toString())) {
                show("请输入要搜索的商品名称");
                return;
            }
        }

        Map<String, String> params = new HashMap<>();
        params.put("current_page", pages + "");
        params.put("page_size", "10");
        params.put("name", editText.getText().toString());
        params.put("classification_id", "");
        if (!TextUtils.isEmpty(type) && type.equals("true")) {
            params.put("last", "1");
        }
        dialog.show();
        Log.e("params", JSON.toJSONString(params));

        HttpUtils.getInstance().POST(mActivity, API.getcommodity, JSON.toJSONString(params), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();
                Log.e("搜索结果：", body);
                if (pages == 1) {
                    list.clear();
                    newsTrl.finishRefreshing();
                } else {
                    newsTrl.finishLoadmore();
                }
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            if (jsonObject.optJSONObject("data") != null) {
                                commoditybean = new Gson().fromJson(body, CommodityBean.class);
                                if (commoditybean.getData().getData() != null && commoditybean.getData().getTotal() > 0) {
                                    List<CommodityBean.DataBeanX.DataBean> list2 = new ArrayList<>();
                                    list.addAll(commoditybean.getData().getData());
                                    Log.e("搜索到的", list.size() + "");
                                    if (list.size() > 0) {
                                        if (SpfUtils.getUserData(mActivity).getType() != 3) {
                                            for (int a = 0; a < list.size(); a++) {
                                                if (list.get(a).getStatus() == 1) {
                                                    list2.add(list.get(a));
                                                }

                                            }
                                            list.clear();
                                            list.addAll(list2);
                                        }
                                        adapter.setdata(mActivity, list, SpfUtils.getUserData(mActivity).getType());
                                        shangpinlist.setAdapter(adapter);
                                        tvNodata.setVisibility(View.GONE);
                                        shangpinlist.setVisibility(View.VISIBLE);
                                    } else {
                                        tvNodata.setVisibility(View.VISIBLE);
                                        shangpinlist.setVisibility(View.GONE);
                                    }
                                } else {
                                    show("没有更多数据了");
                                }
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            searchsp(1);
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });
    }

    /**
     * 选好了
     */
    private void getSelect() {
        SelectOkBean selectok = new SelectOkBean();
        List<SelectOkBean.DataBean> selectoklist = new ArrayList<>();
        if (xuanzhonglist.size() > 0) {
            for (int q = 0; q < xuanzhonglist.size(); q++) {
                Log.e("xuanzhonglist", xuanzhonglist.get(q).getNum());
                SelectOkBean.DataBean databean = new SelectOkBean.DataBean();
                databean.setId(xuanzhonglist.get(q).getId());
                databean.setAmount(xuanzhonglist.get(q).getNum() + "");
                selectoklist.add(databean);
            }
            Log.e("selectok00", JSON.toJSONString(selectoklist));
            List<SelectOkBean.DataBean> newlist = rMList(selectoklist);
            Log.e("selectok1", JSON.toJSONString(newlist));
            for (int q = 0; q < newlist.size(); q++) {
                if (newlist.get(q).getAmount().equals("0.0")) {
                    newlist.remove(q);
                    continue;
                }
            }
            Log.e("selectok2", JSON.toJSONString(newlist));
            Log.e("size", newlist.size() + "");
            if (newlist.size() > 0) {
                selectok.setData(newlist);
                Log.e("selectok", JSON.toJSONString(selectok));
                Log.e("token", SpfUtils.gettoken(mActivity).toString());
                dialog.show();
                HttpUtils.getInstance().POST(mActivity, API.getselectok, JSON.toJSONString(selectok), SpfUtils.gettoken(mActivity).toString(), new HttpUtils.OnOkHttpCallback() {
                    @Override
                    public void onSuccess(String body) {
                        Log.e("选好了上传结果", body);
                        dialog.dismiss();
                        if (!TextUtils.isEmpty(body)) {
                            try {
                                JSONObject jsonObject = new JSONObject(body);
                                int code = jsonObject.optInt("status_code");
                                if (code == 200) {
                                    SpfUtils.clearshangpin(mActivity);
                                        GlobalParms.sChangeFragment.changge(1);
                                    finish();

                                } else if (code == 210) {
                                    String token = jsonObject.optJSONObject("data").optString("token");
                                    SpfUtils.savetoken(mActivity, token);
                                    getSelect();
                                } else if (code == 401) {
                                    show(jsonObject.optString("message"));
                                    SpfUtils.setLogin(mActivity, false);
                                    startActivity(new Intent(mActivity, LoginActivity.class));
                                    mActivity.finish();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Request error, Exception e) {
                        dialog.dismiss();
                        show("访问数据失败，请稍后重试");
                    }
                });
            } else {
                show("请选择商品");
            }
        } else {
            show("请选择商品");
        }


    }

    @Override
    public void doIncrease(View showCountView, final int position) {
        Log.e("jia", ((TextView) showCountView).getText().toString());
        Double add = DoubleUtil.add(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(add + "");
        if (xuanzhonglist != null) {
            if (xuanzhonglist.size() > 0) {
                for (int z = 0; z < xuanzhonglist.size(); z++) {
                    if (xuanzhonglist.get(z).getId() != list.get(position).getId()) {
                        list.get(position).setNum(((TextView) showCountView).getText().toString());
                        xuanzhonglist.add(list.get(position));
                    } else {
                        xuanzhonglist.get(z).setNum(((TextView) showCountView).getText().toString());
                    }
                }
            } else {
                list.get(position).setNum(((TextView) showCountView).getText().toString());
                xuanzhonglist.add(list.get(position));
            }
        }

        SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
    }

    @Override
    public void doDecrease(View showCountView, final int position) {
        Double currentCount = Double.parseDouble(((TextView) showCountView).getText().toString());

        if (currentCount == 0.0) {
            if (xuanzhonglist != null) {
                if (xuanzhonglist.size() > 0) {
                    for (int z = 0; z < xuanzhonglist.size(); z++) {
                        if (xuanzhonglist.get(z).getId() == list.get(position).getId()) {
                            xuanzhonglist.remove(z);
                        }
                    }
                }
            }
            SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
            return;
        }
        if (currentCount < 1.0) {
            ((TextView) showCountView).setText(0 + "");
            if (xuanzhonglist != null) {
                if (xuanzhonglist.size() > 0) {
                    for (int z = 0; z < xuanzhonglist.size(); z++) {
                        if (xuanzhonglist.get(z).getId() == list.get(position).getId()) {
                            xuanzhonglist.remove(z);
                        }
                    }
                }
            }
            SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
            return;
        }
        Double jian = DoubleUtil.sub(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(jian + "");
        if (xuanzhonglist != null) {
            if (xuanzhonglist.size() > 0) {
                for (int z = 0; z < xuanzhonglist.size(); z++) {
                    if (xuanzhonglist.get(z).getId() == list.get(position).getId()) {
                        xuanzhonglist.get(z).setNum(((TextView) showCountView).getText().toString());
                    } else {
                        xuanzhonglist.add(list.get(position));
                    }
                }
            }
        }
        SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
    }

    @Override
    public void doTextView(final View showCountView, final int position) {
        final EditText inputServer = new EditText(mActivity);
        inputServer.setHint("请输入重量");
        inputServer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        inputServer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(inputServer.getText().toString()) || inputServer.getText().toString().equals("0")) {//如果数量 为0，移除数据
                    ((TextView) showCountView).setText("0");
                    Log.e("空", "");
                    if (xuanzhonglist != null) {
                        if (xuanzhonglist.size() > 0) {
                            for (int z = 0; z < xuanzhonglist.size(); z++) {
                                if (xuanzhonglist.get(z).getId() == list.get(position).getId()) {
                                    xuanzhonglist.remove(z);
                                }
                            }
                        }
                    }
                    SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
                    return;
                }
                if (MyUtils.isDoubleOrFloat(inputServer.getText().toString())) {
                    String result = String.format("%.1f", Double.parseDouble(inputServer.getText().toString()));
                    ((TextView) showCountView).setText(result);
                    if (xuanzhonglist != null) {
                        if (xuanzhonglist.size() > 0) {
                            for (int z = 0; z < xuanzhonglist.size(); z++) {
                                if (xuanzhonglist.get(z).getId() != list.get(position).getId()) {
                                    list.get(position).setNum(result);
                                    xuanzhonglist.add(list.get(position));
                                }
                            }
                        } else {
                            list.get(position).setNum(inputServer.getText().toString());
                            xuanzhonglist.add(list.get(position));
                        }
                    }
                    SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
                } else {
                    ((TextView) showCountView).setText("0");//输入的数量不是double类型的，也默认为0，移除数据
                    if (xuanzhonglist != null) {
                        if (xuanzhonglist.size() > 0) {
                            for (int z = 0; z < xuanzhonglist.size(); z++) {
                                if (xuanzhonglist.get(z).getId() == list.get(position).getId()) {
                                    xuanzhonglist.remove(z);
                                }
                            }
                        }
                    }
                    SpfUtils.setshangpin(mActivity, new Gson().toJson(xuanzhonglist));
                }
            }
        });
        builder.show();
    }

    @Override
    public void dochange(View showCountView, int position) {
        startActivityForResult(new Intent(mActivity, CreationFoodActivity.class).putExtra("status", "false")
                .putExtra("listdata", list.get(position)), 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK) {
            searchsp(pages);
        }
    }

    @Override
    public void dodatu(View showCountView, int position) {
        List<CommodityBean.DataBeanX.DataBean.ImgsBean> imlist = list.get(position).getImgs();
        if (imageList != null) {
            imageList.clear();
        }
        for (int a = 0; a < imlist.size(); a++) {
            imageList.add(imlist.get(a).getUrl());
            Log.e("imageListurl", imlist.get(a).getUrl());
        }
        previewDialog = new ImagePreviewDialog(mActivity);
        previewDialog.setData(imageList);
        previewDialog.showDialog(shangpinlist);
    }

    private Set<Integer> setSum;

    private ArrayList rMList(List<SelectOkBean.DataBean> al) {
        setSum = new HashSet<Integer>();
        ArrayList<SelectOkBean.DataBean> newList = new ArrayList();
        if (al != null) {
            for (Iterator iter = al.iterator(); iter.hasNext(); ) {
                SelectOkBean.DataBean element = (SelectOkBean.DataBean) iter.next();
                if (setSum.add(element.getId()))
                    newList.add(element);
            }
        }
        return newList;
    }


}
